package com.chat.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.chat.beans.LoginParam;
import com.chat.chat.beans.User;
import com.chat.chat.beans.kefu;
import com.chat.chat.service.KefuService;
import com.chat.chat.service.LoginParamService;
import com.chat.chat.untils.BussnissExecption;
import com.chat.chat.untils.MD5;
import com.chat.chat.untils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    LoginParamService loginParamService;
    @Resource
    private KefuService kefuService;

    @PostMapping("login")
    public R<Map<String, Object>> login(@RequestBody LoginParam loginParam) {
        HashMap<String, Object> map = new HashMap<>();

        switch (loginParam.getType()) {
            case "0":
                LambdaQueryWrapper<kefu> query = new LambdaQueryWrapper<>();
                kefu kefu = kefuService.getOne(query.eq(com.chat.chat.beans.kefu::getName, loginParam.getName()));
                if (kefu != null) {
                    if (kefu.getPassWord().equals(MD5.encrypt(loginParam.getPassWord()))) {
                        map.clear();
                        map.put("user",kefu);
                        map.put("type",loginParam.getType());
                        return R.ok(map);
                    } else {
                        throw new BussnissExecption("密码错误");
                    }
                } else {
                    throw new BussnissExecption("用户不存在");
                }
            case "1":
                LambdaQueryWrapper<LoginParam> queryWrapper = new LambdaQueryWrapper<>();
                LoginParam loginUser = loginParamService.getOne(queryWrapper.eq(LoginParam::getName, loginParam.getName()));
                if (loginUser != null) {
                    if (loginUser.getPassWord().equals(MD5.encrypt(loginParam.getPassWord()))) {
                        Map<String, Object> login = loginParamService.login(loginUser);
                        login.put("user",loginUser);
                        login.put("type",loginParam.getType());
                        return R.ok(login);
                    } else {
                        throw new BussnissExecption("密码错误");
                    }
                } else {
                    throw new BussnissExecption("用户不存在");
                }

        }
        return null;
    }

    @PostMapping("regiter")
    public void regiter(@RequestBody LoginParam loginParam){
        loginParamService.regiter(loginParam);
    }
}
